package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private OrderTccAction orderTccAction;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        //生成订单id
        //远程调用全局唯一id发号器
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        order.setId(orderId);
        //保存订单
        //orderMapper.create(order);
        // 调用 TccAction 的第一阶段方法
        /*
        orderTccAction 是动态代理对象，有拦截器，
        拦截器中会判断如果没有第一个参数，它会创建上下文对象，再传入原始方法
         */
        orderTccAction.prepareCreateOrder(
                null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());

        //远程调用库存，减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());

        //远程调用账户，扣减账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
